package org.andiv.android.esemeser;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
/**
 * Main activity of esemeser. It is called in three different modes:
 * <ul>
 * <li>Main interface for create and edit message data</li>
 * - when triggered as main activity 
 * <li>While creating shortcut as a list for choosing what message will be send in shortcut</li>
 * - when triggered with intent filled with extra {@link #SMS_ACTION} tag and {@link #SHORTCUT} value 
 * (eg. 
 * <code>
 * someIntent.putExtra(MsgChooser.SMS_ACTION, MsgChooser.SHORTCUT);
 * startActivity(someIntent, 0);
 * </code>
 * <li>Actually sending message when shortcut is activated</li>
 * - when triggered with intent filled with extra {@link #SMS_ACTION} tag and {@link #RUNSHORTCUT} value like in {@link MsgShortcut} 
 * </ul>
 * @author andrej
 *
 */
public class MsgChooser extends ListActivity {
    /**
     * Caller action for creating shortcut
     */
    public static final String SHORTCUT = "shortcut";
    /**
     * Caller action for running shortcut
     */
    public static final String RUNSHORTCUT = "runshortcut";
    /**
     * Data tag for msgdata record id
     */
    public static final String MSG_ID = "org.andiv.android.esemeser.Id";
    /**
     * Tag for storing caller action eg. if (getIntent().getStringExtra(SMS_ACTION).equals(RUNSHORTCUT))...
     */
    public static final String SMS_ACTION = "org.andiv.android.esemeser.Actn";
    /** Called when the activity is first created. */
//    private static final String TAG="org.andiv.android.esemeser.MsgChooser";
    private static final String SENT_INTENT="org.andiv.android.esemeser.MsgChooser.SENT";
    private static final String DELIVERED_INTENT="org.andiv.android.esemeser.MsgChooser.DELIVERED";
    /**
     * Data tag for msgdata.disptext
     */
    public static final String MSG_DESC = "org.andiv.android.esemeser.DispText";
    /**
     * Data tag for msgdata.iconpath
     */
    public static final String MSG_ICON = "org.andiv.android.esemeser.IconRes";
    private static Cursor c;
    private static Db db;
    private static MsgChooser inst;
    /**
     * @return cursor binded to this list activity 
     */
    public static Cursor getCursor() {
      return c;
    }
    /**
     * @return database displayes in this list
     */
    public static Db getDb() {
      if (db==null) db = new Db(inst);
      return db;
    }
    private static String callerActn;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        inst = this;
        getDb();
        callerActn = getIntent().getStringExtra(SMS_ACTION);
        
        if (RUNSHORTCUT.equals(callerActn)) {//run as shortcut for 1 sms
          int smsid = getIntent().getIntExtra(MsgChooser.MSG_ID, -1);
          if (smsid >= 0) {
            sendMessage(smsid);
          }
        } else {//setup execution
          c = db.getWritableDatabase().query("msgdata", new String[] {"_id","disptext"}, null, null, null, null, "srt");
          if (c.getCount() == 0) {
            db.populateTestData(db.getWritableDatabase());
            c.requery();
          }
          ListAdapter la = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, c, new String[] {"disptext"}, new int[] {android.R.id.text1});
          registerForContextMenu(getListView());
          getListView().setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView p, View v, int pos,
                long id) {
//              Log.d(TAG,"CP:"+c.getString(1)+"; Pos:"+pos+"; id="+id);
              if (SHORTCUT.equals(callerActn)) {
                Intent resdata = new Intent();//brijem da mi ne treba tu ovo: getBaseContext(), MsgShortcut.class);
                resdata.putExtra(MsgChooser.MSG_ID, c.getInt(0));
                resdata.putExtra(MsgChooser.MSG_DESC, c.getString(1));
                setResult(RESULT_OK, resdata);
                finish();
              } else {
                sendMessage(c.getInt(0));
              }
            }
          });
          setListAdapter(la);
        }

        //common
        registerReceiver(new BroadcastReceiver() {
          public void onReceive(Context context, Intent intent) {
            int tmsg;
            if (getResultCode() == Activity.RESULT_OK) {
              tmsg = R.string.SMSsent;
            } else {
              tmsg = R.string.SMSNOTsent;
            }
            Toast.makeText(getBaseContext(), tmsg, Toast.LENGTH_LONG).show();
            if (RUNSHORTCUT.equals(callerActn)) {
              finish();
            }
          }
        }, new IntentFilter(SENT_INTENT));
          
    }
    /**
     * Sends a message defined with smsid in default database
     * @param smsid row id of msgdata to send
     */
    public static void sendMessage(int smsid) {
      final Cursor mc = db.getReadableDatabase().query("msgdata", new String[] {"phone","bodytext"}, "_id = "+smsid, null, null, null, null);
      if (mc.getCount() == 0) {
        Toast.makeText(inst, "No message data for id = "+smsid, Toast.LENGTH_LONG).show();
        return;
      }
      mc.moveToFirst();
      if (mc.isNull(0) || mc.isNull(1)) {
        Toast.makeText(inst, R.string.invalidSMSData, Toast.LENGTH_LONG).show();
        return;
      } 
      String text = inst.getResources().getString(R.string.sendQuestion).replaceFirst("[?]", mc.getString(1)).replaceFirst("[?]", mc.getString(0));
      AlertDialog.Builder adb = new AlertDialog.Builder(inst);
      adb.setMessage(text).setTitle(R.string.sendTitle);
      adb.setPositiveButton(R.string.sendOK, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
          PendingIntent sint = PendingIntent.getBroadcast(inst, 0, new Intent(SENT_INTENT), 0); 
          PendingIntent dint = PendingIntent.getBroadcast(inst, 0, new Intent(DELIVERED_INTENT), 0); 
          SmsManager.getDefault().sendTextMessage(mc.getString(0), null, mc.getString(1), sint, dint);
        }
      });
      adb.setNegativeButton(R.string.sendCancel, new DialogInterface.OnClickListener() {
        
        public void onClick(DialogInterface dialog, int which) {
          dialog.dismiss();
          if (RUNSHORTCUT.equals(callerActn)) {
            inst.finish();
          }
        }
          
      });
      adb.show();
    }
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
      ContextMenuInfo menuInfo) {
      menu.setHeaderTitle("Actions");
      menu.add(Menu.NONE,0,0,R.string.mnu_Duplicate);
      menu.add(Menu.NONE,1,1,R.string.mnu_Modify);
      menu.add(Menu.NONE,2,2,R.string.mnu_Delete);
    }
    @Override
    public boolean onContextItemSelected(MenuItem item) {
//      AdapterContextMenuInfo nfo = (AdapterContextMenuInfo)item.getMenuInfo();
//      tl("Picked "+nfo.id+"\n Cursor.disptext "+c.getString(1)+"\n Cursor._id "+c.getInt(0)+"\n MenuPicked "+item.getItemId()+" ("+item.getTitle()+")");
      switch (item.getItemId()) {
        case 0: //Duplicate
          duplicateRec(c.getInt(0));
          break;
        case 1:
          modifyRec(c.getInt(0));
          break;
        case 2:
          deleteRec(c.getInt(0));
          break;
        default:
          Toast.makeText(this, "Not implemented yet :(", Toast.LENGTH_SHORT).show();
      }
        
      return true;
    }
    private void deleteRec(final int _id) {
      AlertDialog.Builder adb = new AlertDialog.Builder(this);
      adb.setMessage(R.string.alertDelete).setTitle(R.string.alertDeleteTitle);
      adb.setPositiveButton(R.string.alertDeleteOK, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
          db.deleteMsgdata(_id);
          c.requery();
        }
      });
      adb.setNegativeButton(R.string.alertDeleteCancel, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
          dialog.dismiss();
        }
      });
      adb.show();
    }
    private void modifyRec(int _id) {
//      Log.d(TAG,"modifyRec "+_id);
      Intent i = new Intent(this, MsgEditor.class);
      i.putExtra(MSG_ID, _id);
      i.putExtra(SMS_ACTION, "modify");
      startActivity(i);
    }
    private void duplicateRec(int _id) {
//      Log.d(TAG,"duplicateRec "+_id);
      long id = db.duplicateMsgData(_id);
      c.requery();
      modifyRec((int)id);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
      getMenuInflater().inflate(R.menu.choosermenu, menu);
      return true;
    };
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
      switch (item.getItemId()) {
        case R.id.itemPopulateZGParking:
          populateZGPark();
          break;
        case R.id.itemPopulateVIP:
          db.populateVIP(db.getWritableDatabase());
          break;
        case R.id.itemPopulateZET:
          db.populateZET(db.getWritableDatabase());
          break;
        case R.id.itemDeleteAll:
          deleteAll();
          break;
        default:
          //nothing
      }
      c.requery();
      return true;
    }
    /**
     * Deletes all records in list (and msgdata table) with previous confirmation message
     */
    private void deleteAll() {
      AlertDialog.Builder adb = new AlertDialog.Builder(this);
      adb.setMessage(R.string.alertDeleteAll).setTitle(R.string.alertDeleteTitle);
      adb.setPositiveButton(R.string.alertDeleteOK, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
          db.deleteAllMsgdata();
          c.requery();
        }
      });
      adb.setNegativeButton(R.string.alertDeleteCancel, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
          dialog.dismiss();
        }
      });
      adb.show();
    }
    /**
     * Populates data for Zagreb m-parking with custom {@link AlertDialog} for input license plate number 
     */
    private void populateZGPark() {
      final View dv = View.inflate(this,R.layout.populate, null);
      AlertDialog.Builder adb = new AlertDialog.Builder(this);
      adb.setTitle(R.string.alertPopulateTitle);
      adb.setPositiveButton(R.string.alertPopulateOK, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
          String plate = ((EditText)dv.findViewById(R.id.editPlateNo)).getText().toString();
          db.populateZgParkingData(db.getWritableDatabase(), plate);
          c.requery();
        }
      });
      adb.setNegativeButton(R.string.alertPopulateCancel, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
          dialog.dismiss();
        }
      });
      adb.setView(dv);
      adb.show();      
    }
}